#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cerrno>
#include<cstdlib>
#include <cstring>
#include "Log.hpp"

enum error
{
    SOCKET_ERR = 1,
    BIND_ERR,
    USAGE_ERR,

};
class UdpServer
{
public:
    UdpServer(uint16_t port) : _port(port), _socketfd(-1)
    {
    }
    void InitServer()
    {
        // 1.创建UDP socket套接字
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            LOG(FATAL, "socket error,%d,%s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        LOG(INFO, "create socket success,socket:%d", _socketfd);

        // 填充struct sockaddr_in结构
        struct sockaddr_in local;
        bzero(&local, sizeof(local)); // 对空间进行清0
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr=INADDR_ANY;//这个数就是0，因为是0，大小端也就没意义了
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());

        int n = bind(_socketfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error,%d,%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        LOG(INFO, "bind success");
    }
    void start()
    {
        while (true)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            ssize_t n=recvfrom(_socketfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
            if(n>0)
            {
                buffer[n]=0;
                LOG(DEBUG,"get message from[%s,%d]:%s",inet_ntoa(peer.sin_addr),ntohs(peer.sin_port),buffer);//这样解析就知道是谁发过来的
                sendto(_socketfd,buffer,strlen(buffer),0,(struct sockaddr*)&peer,len);
            }
        }
    }

private:
    int _socketfd;
    // std::string _ip;
    uint16_t _port;
};